package com.xpsoft.oa.workflow.event;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.listener.EventListener;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.OpenProcessInstance;

import com.xpsoft.core.util.AppUtil;
import com.xpsoft.oa.model.flow.ProcessRun;
import com.xpsoft.oa.model.produce.MaterialDumping;
import com.xpsoft.oa.model.system.AppUser;
import com.xpsoft.oa.service.flow.ProcessRunService;
import com.xpsoft.oa.service.produce.MaterialDumpingService;
import com.xpsoft.oa.service.system.AppUserService;
import com.xpsoft.oa.service.system.DepartmentService;

public class MaterialDumpingFinishListener implements EventListener{
	private Log logger=LogFactory.getLog(MaterialDumpingFinishListener.class);
	@Override
	public void notify(EventListenerExecution execution) throws Exception {
		//获取表单参数
		OpenProcessInstance pi=execution.getProcessInstance();
		String deptId = (String)pi.getVariable("materialDumping.dept.depId");
		String applyUserId = (String)pi.getVariable("materialDumping.applyUser.userId");
		Date applyDate = (Date)pi.getVariable("materialDumping.applyDate");
		String dataList = (String)pi.getVariable("materialDumping.dataList");
		
		MaterialDumping materialDumping = new MaterialDumping();
		materialDumping.setApplyDate(applyDate);
		AppUserService appUserService = (AppUserService)AppUtil.getBean("appUserService");
		if(StringUtils.isNotBlank(applyUserId)){
			materialDumping.setApplyUser(appUserService.get(Long.valueOf(applyUserId)));
		}
		if(StringUtils.isNotBlank(deptId)){
			DepartmentService departmentService = (DepartmentService)AppUtil.getBean("departmentService");
			materialDumping.setDept(departmentService.get(Long.valueOf(deptId)));
		}
		
		ProcessRunService processRunService=(ProcessRunService)AppUtil.getBean("processRunService");
		ProcessRun processRun=processRunService.getByExeId(pi.getId());
		materialDumping.setProcessRunId(processRun.getRunId());
		
		MaterialDumpingService materialDumpingService = (MaterialDumpingService)AppUtil.getBean("materialDumpingService");
		materialDumpingService.saveMaterialDumping(materialDumping, dataList);
		
		
		//获取流程发起者对象
		AppUser flowStartUser=(AppUser)execution.getProcessInstance().getVariable("flowStartUser");
	
		//所有参与流程的都发消息
		AppUtil.sendSysShortMsg(execution.getProcessInstance().getId(), flowStartUser);
	}

}
